package api;

import api.betfairAPI.BetfairAPI;
import api.betfairAPI.BetfairAPICallRate;
import com.google.common.base.Optional;
import org.apache.axis2.AxisFault;
import org.apache.log4j.Logger;
import utils.Display;

import java.util.concurrent.ScheduledExecutorService;

/**
 * User: Darren
 * Date: 7/04/13
 * Time: 11:57 AM
 */
public class APIFactory {
    private static Logger logger = Logger.getLogger(APIFactory.class);
    private ScheduledExecutorService scheduler;
    private Display display;
    private Optional<BetfairAPI> betfairAPIOptional = Optional.absent();
    private Optional<BetfairAPI> betfairFreeAccessAPIOptional = Optional.absent();
    private static final int BETFAIR_API_FREE_ACCESS_API_ID = 82;
    private static final int BETFAIR_API_TBD_PAID_API_ID = 0;

    public APIFactory(ScheduledExecutorService scheduler, Display display) {
        this.scheduler = scheduler;
        this.display = display;
    }

    public API getAPI(APITypes apiType) throws AxisFault, RuntimeException {
        switch(apiType) {
            case BETFAIR:
                if (betfairAPIOptional.isPresent()) {
                    return betfairAPIOptional.get();
                }
                betfairAPIOptional = Optional.of(new BetfairAPI(new BetfairAPICallRate(BETFAIR_API_TBD_PAID_API_ID)));
                return betfairAPIOptional.get();
            case BETFAIR_FREE_ACCESS:
                if (betfairFreeAccessAPIOptional.isPresent()) {
                    return betfairFreeAccessAPIOptional.get();
                }
                betfairFreeAccessAPIOptional = Optional.of(new BetfairAPI(
                        new BetfairAPICallRate(BETFAIR_API_FREE_ACCESS_API_ID, scheduler, display)));
                return betfairFreeAccessAPIOptional.get();
            default:
                logger.fatal("Request to instantiate unknown API type: " + apiType);
                throw new RuntimeException();
        }
    }
}
